package jiuwu.gqz.audiorecord

import android.media.MediaExtractor
import android.media.MediaFormat
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import java.io.File
import java.util.concurrent.Executors

class MainActivity : AppCompatActivity(), View.OnTouchListener {

    var TAG = "MainActivity-->"

    var info: TextView? = null
    var record: Button? = null
    var audioRecordHelper: AudioRecordHelper? = null
    var audioPlayHelper: AudioPlayDecoder? = null

    var pool = Executors.newFixedThreadPool(1)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        info = findViewById(R.id.info)
        record = findViewById(R.id.record)
        record!!.setOnTouchListener(this)

//        getMp4MediaFormat()
    }

    fun OnClick(view: View) {
        when (view.id) {
            R.id.play -> {
                Log.i(TAG, "play")
                audioPlayHelper = AudioPlayDecoder()
                audioPlayHelper!!.start()
            }
            else -> {
            }
        }
    }

    override fun onTouch(v: View?, event: MotionEvent?): Boolean {
        when (event!!.action) {
            MotionEvent.ACTION_DOWN -> {
                audioRecordHelper = AudioRecordHelper()
                audioRecordHelper!!.isRecording = true
                pool.submit({
                    Log.i(TAG, "startRecord")
                    audioRecordHelper!!.start()
                    Log.i(TAG, "startRecord over")
                })
            }
            MotionEvent.ACTION_UP -> {
                audioRecordHelper!!.isRecording = false
                Log.i(TAG, "stopRecord")
            }
            else -> {
            }
        }
        return false
    }

    fun getMp4MediaFormat() {
        var path = Environment.getExternalStorageDirectory().path + "/Download/test.mp4"
        var mediaExtractor = MediaExtractor()
        mediaExtractor.setDataSource(path)
        var trackCount = mediaExtractor.trackCount
        for (i in 0 until trackCount) {
            var format = mediaExtractor.getTrackFormat(i)
            if (format.getString(MediaFormat.KEY_MIME).startsWith("audio")) {
                Log.i(TAG, "getMp4MediaFormat: " + format.toString())
            }
        }
    }

}